const URLProcessor = require('./src/utils/urlProcessor');
const VideoDownloader = require('./src/services/videoDownloader');
const TextExtractor = require('./src/services/textExtractor');
const fs = require('fs');

async function extractTextFromVideoUrl(shareUrl) {
    const urlProcessor = new URLProcessor();
    const videoDownloader = new VideoDownloader();
    const textExtractor = new TextExtractor();

    try {
        // 1. 提取视频ID
        const videoId = await URLProcessor.extractDouyinVideoId(shareUrl);
        if (!videoId) {
            throw new Error('无法解析视频链接');
        }

        // 2. 下载视频
        const videoPath = await videoDownloader.downloadVideo(videoId);
        if (!videoPath) {
            throw new Error('视频下载失败');
        }

        // 3. 提取文字
        const textContent = await textExtractor.extractText(videoPath);

        // 4. 清理临时文件
        fs.unlinkSync(videoPath);

        return textContent || '未能识别到文字内容';
    } catch (error) {
        console.error('处理失败:', error.message);
        return `处理失败: ${error.message}`;
    }
}

// 测试用例
if (require.main === module) {
    const readline = require('readline').createInterface({
        input: process.stdin,
        output: process.stdout
    });

    readline.question('请输入抖音分享链接：', async (url) => {
        const result = await extractTextFromVideoUrl(url);
        console.log('提取的文案内容：');
        console.log(result);
        readline.close();
    });
}